package cn.itsource.basic.base.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class UploadController {

    @PostMapping
    public AjaxResult uploadFile(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String fileName = file.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
           e.printStackTrace();
           return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙,请稍后重试!");
        }
    }
    //localhost:8080/xxxx?id=1
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam(value = "path",required = true) String path){
        //   /group1/M00/00/69/CgAIC2LD8riAF0J7AAIl5Q-U_lE362.jpg
        String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
        String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
        String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
        boolean flag = FastdfsUtil.delete(groupName, remotePath);
        if(flag){
            return AjaxResult.me();
        }else{
            return AjaxResult.me().setSuccess(flag).setMessage("服务器繁忙,请稍后重试!");
        }
    }
}
